package com.sh.production;

import com.sh.bean.RssNewsBuffer;
import com.sh.expend.NewsWriterTask;
import org.apache.log4j.Logger;

import java.io.BufferedReader;
import java.io.FileReader;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class NewsSystem implements Runnable {
    private String sourcePath;   // source.txt源文件路径
    private ScheduledThreadPoolExecutor executor;  // 定时任务线程池
    private RssNewsBuffer buffer;

    private static Logger log = Logger.getLogger(NewsSystem.class.getName());


    public NewsSystem(String sourcePath) {
        this.sourcePath = sourcePath;
        this.executor = new ScheduledThreadPoolExecutor(Runtime.getRuntime().availableProcessors());
        this.buffer = new RssNewsBuffer();
    }

    @Override
    public void run() {
        // 消费任务创建 启动
        NewsWriterTask writerTask = new NewsWriterTask(buffer);
        new Thread(writerTask).start();

        // 读 sources.txt中的rss源的有几个，有几个就几个线程
        Path file = Paths.get(sourcePath);
        try (
                // 读取文件可以按行读
                BufferedReader reader = new BufferedReader(new FileReader(file.toFile()))
        ) {
            String line;
            // 按行读取 source.txt 文件
            while ((line = reader.readLine()) != null) {
                String[] strs = line.split(";");
                if (strs != null && strs.length == 2) {
                    String rssName = strs[0];
                    String rssUrl = strs[1];
                    // 一行一个生产者任务
                    NewsProductTask ProductTask = new NewsProductTask(rssName, rssUrl, buffer);
                    // 启动生产者任务 scheduleWithFixedDelay   每5秒执行一次
                    this.executor.scheduleWithFixedDelay(ProductTask, 0, 5, TimeUnit.SECONDS);
                }
            }
        } catch (Exception e) {
            log.error("读取RSS源文件数量异常  " + e);
            e.printStackTrace();
        }
    }
}
